package com.explorer.ider.bootguide.utils;

import android.annotation.TargetApi;
import android.app.backup.BackupManager;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;

import com.explorer.ider.bootguide.R;
import com.explorer.ider.bootguide.itembean.LocaleInfo;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

/**
 * Created by Eric on 2016/9/5.
 */
public class LanguageChangeUtils {

    private static final String TAG = "LanguageChangeUtils";

    public static void updateLanguage(Locale locale) {
        try {
            Object objIActMag, objActMagNative;

            Class clzIActMag = Class.forName("android.app.IActivityManager");

            Class clzActMagNative = Class
                    .forName("android.app.ActivityManagerNative");

            //amn = ActivityManagerNative.getDefault();
            Method mtdActMagNative$getDefault = clzActMagNative
                    .getDeclaredMethod("getDefault");

            objIActMag = mtdActMagNative$getDefault.invoke(clzActMagNative);

            // objIActMag = amn.getConfiguration();
            Method mtdIActMag$getConfiguration = clzIActMag
                    .getDeclaredMethod("getConfiguration");

            Configuration config = (Configuration) mtdIActMag$getConfiguration
                    .invoke(objIActMag);

            // set the locale to the new value
            config.locale = locale;

            //持久化   config.userSetLocale = true;
            Class clzConfig = Class
                    .forName("android.content.res.Configuration");
            java.lang.reflect.Field userSetLocale = clzConfig
                    .getField("userSetLocale");
            userSetLocale.set(config, true);

            // 此处需要声明权限:android.permission.CHANGE_CONFIGURATION
            // 会重新调用 onCreate();
            Class[] clzParams = { Configuration.class };

            // objIActMag.updateConfiguration(config);
            Method mtdIActMag$updateConfiguration = clzIActMag
                    .getDeclaredMethod("updateConfiguration", clzParams);

            mtdIActMag$updateConfiguration.invoke(objIActMag, config);

            BackupManager.dataChanged("com.android.providers.settings");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static List<LocaleInfo> getAllAssetLocales(Context context, boolean isInDeveloperMode) {
        final Resources resources = context.getResources();
        //获取系统所支持的语言
        final String[] locales = Resources.getSystem().getAssets().getLocales();
        List<String> localeList = new ArrayList<String>(locales.length);
        Collections.addAll(localeList, locales);

        // Don't show the pseudolocales unless we're in developer mode.
        if (!isInDeveloperMode) {
            localeList.remove("ar-XB");
            localeList.remove("en-XA");
        }

        Collections.sort(localeList);
        final String[] specialLocaleCodes = resources.getStringArray(R.array.special_locale_codes);
        final String[] specialLocaleNames = resources.getStringArray(R.array.special_locale_names);

        final ArrayList<LocaleInfo> localeInfos = new ArrayList<LocaleInfo>(localeList.size());
        for (String locale : localeList) {
            final Locale l = Locale.forLanguageTag(locale.replace('_', '-'));
            if (l == null || "und".equals(l.getLanguage())
                    || l.getLanguage().isEmpty() || l.getCountry().isEmpty()) {
                continue;
            }

            if (localeInfos.isEmpty()) {
                localeInfos.add(new LocaleInfo(toTitleCase(l.getDisplayLanguage(l)), l));
            } else {
                // check previous entry:
                //  same lang and a country -> upgrade to full name and
                //    insert ours with full name
                //  diff lang -> insert ours with lang-only name
                final LocaleInfo previous = localeInfos.get(localeInfos.size() - 1);
                if (previous.locale.getLanguage().equals(l.getLanguage()) &&
                        !previous.locale.getLanguage().equals("zz")) {
                    previous.label = toTitleCase(getDisplayName(
                            previous.locale, specialLocaleCodes, specialLocaleNames));
                    localeInfos.add(new LocaleInfo(toTitleCase(
                            getDisplayName(l, specialLocaleCodes, specialLocaleNames)), l));
                } else {
                    String displayName = toTitleCase(l.getDisplayLanguage(l));
                    localeInfos.add(new LocaleInfo(displayName, l));
                }
            }
        }

        Collections.sort(localeInfos);
        return localeInfos;
    }

    //获得全部Locale对象，然后遍历出这些对象
    private static String[] simpleList = new String[]{"en_US","zh_TW","zh_CN","pt_BR","es_ES","ru_RU","fr_FR","de_DE","pt_PT","ja_JP"};
    private static String[] simpleListName = new String[]{"English","中文（繁體）","中文（简体）","Português (Brasil)",
            "Español","русский","français","Deutsch","Português","日本語"};
    public static List<LocaleInfo> getSimpleLanguageList(Context context){
        //排除获取
        List<LocaleInfo> allListInfo = getAllAssetLocales(context,true);
        List<LocaleInfo> listLocale = new ArrayList<>();
        for (int i = 0; i < simpleList.length; i++) {
            for (int j = 0; j < allListInfo.size(); j++) {
                String s = allListInfo.get(j).getLocale().getLanguage() + "_"+
                        allListInfo.get(j).getLocale().getCountry();
                if(s.equals(simpleList[i])) {
                    listLocale.add(allListInfo.get(j));
                }
            }
        }
             return listLocale;
//        //new对象获取
//        List<LocaleInfo> listInfo = new ArrayList<LocaleInfo>();
//        List<Locale> listLocale = new ArrayList<Locale>();
//        for (int i = 0; i < simpleList.length; i++) {
//            listLocale.add(new Locale(simpleList[i]));
//            listInfo.add(new LocaleInfo(simpleListName[i],listLocale.get(i)));
//        }
//        return listInfo;
    }

    private static String toTitleCase(String s) {
        if (s.length() == 0) {
            return s;
        }

        return Character.toUpperCase(s.charAt(0)) + s.substring(1);
    }

    private static String getDisplayName(
            Locale l, String[] specialLocaleCodes, String[] specialLocaleNames) {
        String code = l.toString();

        for (int i = 0; i < specialLocaleCodes.length; i++) {
            if (specialLocaleCodes[i].equals(code)) {
                return specialLocaleNames[i];
            }
        }

        return l.getDisplayName(l);
    }

}
